package com.czl.module_storehouse.adapter;

import android.annotation.SuppressLint;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.czl.base.data.bean.tengyun.LocatListBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.data.bean.tengyun.SortBeanType;
import com.czl.base.util.SpHelper;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.widget.CommonCounterView;

import java.util.List;

/**
 * @author xubin
 */
public class RemandNeedAdapter extends BaseMultiItemQuickAdapter<SortBean, BaseViewHolder> {

    public static final int TAG_RECEIVE = 1;
    public static final int TAG_BORROW = 2;
    private final int tag;
    private final OnNumberChangedListener mOnNumberChangedListener;
    private final int mStorehouseLocationId = SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_ID);
    private final String locationName = SpHelper.INSTANCE.decodeString(Constants.SpKey.STOREHOUSE_LOCATION_NAME);

    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    public RemandNeedAdapter(List<SortBean> data, int tag, OnNumberChangedListener onNumberChangedListener) {
        super(data);
        this.tag = tag;
        mOnNumberChangedListener = onNumberChangedListener;
        addItemType(SortBeanType.Type.VIEW_TYPE_PRODUCT, R.layout.item_remand_product);
        addItemType(SortBeanType.Type.VIEW_TYPE_SORT, R.layout.item_remand_sort);
    }

    private String getType() {
        if (TAG_RECEIVE == tag) {
            return "已领：";
        } else {
            return "已借：";
        }
    }

    @Override
    protected void convert(@NonNull BaseViewHolder helper, SortBean item) {
        int viewType = helper.getItemViewType();
        helper.setText(R.id.tv_title, item.getSortName())
                .setText(R.id.tv_model, "型号：" + item.getSortModel())
                .setText(R.id.tv_num, "数量：" + item.getApplyNum())
                .setText(R.id.tv_type, getType())
                .setText(R.id.tv_remand_num, "已还：" + item.getReturnNum())
                .setText(R.id.tv_receive_num, String.valueOf(item.lendNum()))
                .setText(R.id.tv_damage_num, "损坏：" + item.excNum());
        helper.getView(R.id.tv_damage_num)
                .setOnClickListener(v -> {
                    if (getOnItemChildClickListener() != null) {
                        getOnItemChildClickListener().onItemChildClick(RemandNeedAdapter.this, v, helper.getLayoutPosition() - getHeaderLayoutCount());
                    }
                });
        helper.getView(R.id.cl_root)
                .setOnClickListener(v -> {
                    if (item.getRemandNum() == 0) {
                        return;
                    }
                    if (getOnItemChildClickListener() != null) {
                        getOnItemChildClickListener().onItemChildClick(RemandNeedAdapter.this, v, helper.getLayoutPosition() - getHeaderLayoutCount());
                    }
                });
        if (SortBeanType.Type.VIEW_TYPE_SORT == viewType) {
            helper.setText(R.id.tv_loc, "位置：" + item.getLocText(SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_ID), locationName));
            TextView tvLoc = helper.getView(R.id.tv_loc);
            tvLoc.setOnClickListener(v -> {
                if (getOnItemChildClickListener() != null) {
                    getOnItemChildClickListener().onItemChildClick(RemandNeedAdapter.this, v, helper.getLayoutPosition() - getHeaderLayoutCount());
                }
            });
            setCommonView(helper, item, helper.getAbsoluteAdapterPosition() - getHeaderLayoutCount());
        } else {
            helper.setText(R.id.tv_return_num, String.valueOf(item.getProductCount()))
                    .setText(R.id.tv_loc, "位置：" + item.getLocTextByProducts(locationName));
//                    .setGone(R.id.iv_right, item.getRemandNum() > 0);
        }
    }

   /* @Override
    protected void convertPayloads(@NonNull BaseViewHolder helper, SortBean item, @NonNull List<Object> payloads) {
        super.convertPayloads(helper, item, payloads);
        helper.setText(R.id.tv_damage_num, "损坏：" + item.getExcNumInt());
    }*/

    private void setCommonView(BaseViewHolder holder, SortBean item, int position) {
        CommonCounterView commonCounterView = holder.getView(R.id.countView);
        commonCounterView.setTouchItemPosition(position);
        commonCounterView.setTag(position);
        commonCounterView.setMaxCount(item.getRemandNum());
        commonCounterView.setCount(getCurrentNum(item));
        commonCounterView.setMinCount(commonCounterView.getCount() - (item.getDefaultStockNum() == null ? 0 : item.getDefaultStockNum()));
        commonCounterView.setTextChangeListener((view, count) -> {
            int tag = (int) view.getTag();
            SortBean sortBean = getData().get(tag);
            changeSortBean(holder, sortBean, count, commonCounterView.getMinCount());
            if (mOnNumberChangedListener != null) {
                mOnNumberChangedListener.textChange(sortBean);
            }
        });
    }

    /**
     * 当前显示数量
     *
     * @param sortBean
     * @return
     */
    public int getCurrentNum(SortBean sortBean) {
        if (sortBean.getLocatList() == null) {
            return 0;
        }
        int totalCount = 0;
        for (LocatListBean locatListBean : sortBean.getLocatList()) {
            int storehouseLocatId = locatListBean.getStorehouseLocatId();
            int stockNumInt = locatListBean.getStockNumInt();
            totalCount += stockNumInt;
            if (storehouseLocatId == mStorehouseLocationId) {
                sortBean.setDefaultStockNum(sortBean.stockNum());
            }
        }
        return totalCount;
    }

    @SuppressLint("SetTextI18n")
    private void changeSortBean(BaseViewHolder holder, SortBean sortBean, int count, int minCount) {
        sortBean.setStorageNum(count);
        sortBean.setInventoryNum(count);
        sortBean.setStockNum(count);
        if (count > minCount) {
            //添加临时仓库
            sortBean.setDefaultLocatStock(count, mStorehouseLocationId, locationName);
        } else {
            //移出临时仓位数据
            sortBean.removeDefaultLocat(mStorehouseLocationId);
        }
        TextView tvLoc = holder.getView(R.id.tv_loc);
        String text = sortBean.getLocText(mStorehouseLocationId, locationName);
        tvLoc.setText("位置：" + text);
    }

    public interface OnNumberChangedListener {
        void textChange(SortBean sortBean);
    }
}
